package com.cn.example.demo.config.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cn.example.demo.config.exception.custum.DataException;
import com.cn.example.demo.config.exception.custum.ServiceException;
import com.cn.example.demo.config.restful.RestResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 异常统一处理
 * 
 * @author yhr
 */
@ControllerAdvice
public class GlobalExceptionHandler {
	private static final Logger logger = LogManager.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object logicExceptionHandler(HttpServletRequest request, Exception e, HttpServletResponse response) {
        //系统级异常，错误码固定为505，提示语固定为系统繁忙，请稍后再试
        RestResult result = new RestResult(false, "505", e.getMessage(), ErrorMessage.SYSTEM_EXCEPTION);
        //如果是业务逻辑异常，返回具体的错误码与提示信息
        if (e instanceof DataException) {
        	DataException dataException = (DataException) e;
            result.setCode(dataException.getCode());
            result.setErrorMessage(dataException.getErrorMsg());
        } else if (e instanceof ServiceException) {
        	ServiceException serviceException = (ServiceException) e;
            result.setCode(serviceException.getCode());
            result.setErrorMessage(serviceException.getErrorMsg());
        } else {
            //对系统级异常进行日志记录
            logger.error("系统异常:" + e.getMessage(), e);
        }
        try {
			return new ObjectMapper().writeValueAsString(result);
		} catch (JsonProcessingException jpe) {
			logger.info("---->JSON转化异常。。。");
			jpe.printStackTrace();
			return null;
		}
    }
}
